package com.myqf.d7_日期类_druid连接池.dao设计模式.dao.impl;


import com.myqf.d7_日期类_druid连接池.dao设计模式.User;
import com.myqf.d7_日期类_druid连接池.dao设计模式.dao.UserDao;
import com.myqf.d7_日期类_druid连接池.jdbc连接池.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 作者：黎杭
 * 日期：2020/2/18
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User findUserById(int i) throws SQLException {// 在这里就是真正的去访问数据了

        // 第一步，拿到Connection对象

        Connection connection = ConnectionPool.getConnection();
        String sql = "select * from user where id=?";// sql语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, i);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            User u = new User();
            int userId = resultSet.getInt(1);
            String name = resultSet.getString(2);
            int age = resultSet.getInt(3);
            String phone = resultSet.getString(4);
            String pwd = resultSet.getString(5);
            u.setUserId(userId);
            u.setAge(age);
            u.setName(name);
            u.setPhone(phone);
            u.setPwd(pwd);
            return u;// 直接返回用户对象
        }
        return null;
    }
}
